package com.repair.miniApp.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.repair.common.core.domain.AjaxResult;
import com.repair.common.utils.http.HttpUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/openid")
public class OpenIdController {

    private final static String AppID = "wx5dc2461f0b4f3e77";
    private final static String AppSecret = "9f576667422364f930cd3b67efa50374";

    @GetMapping("/get_openid")
    public AjaxResult getWechatLoginInfo(String code) {
        if (StrUtil.isEmpty(code)) {
            return AjaxResult.error("缺少code参数");
        }

        try {
            // 构建带有参数的完整URL，不使用URLEncoder
            String fullUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppID
                    + "&secret=" + AppSecret.trim()
                    + "&js_code=" + code
                    + "&grant_type=authorization_code";

            // 发送GET请求并获取响应结果
            String json = HttpUtils.sendGet(fullUrl);

            // 添加调试信息
            System.out.println("Response from WeChat API: " + json);

            // 解析JSON响应
            JSONObject jsonObject = JSONUtil.parseObj(json);
            String session_key = (String) jsonObject.get("session_key");
            String openid = (String) jsonObject.get("openid");
            String errcode = (String) jsonObject.get("errcode");
            // 检查是否成功获取到 openid
            if (StrUtil.isEmpty(openid)) {
                String errMsg = jsonObject.containsKey("errmsg") ? (String) jsonObject.get("errmsg") : "未获取到openid";
                return AjaxResult.error(errMsg);
            }

            // 生成token并构造返回数据
            String token = UUID.randomUUID().toString();
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("session_key", session_key);
            data.put("openid", openid);
            data.put("errcode",errcode);

            return AjaxResult.success(data);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("处理过程中出现异常：" + e.getMessage());
        }
    }
}